<template>
  <hx-page>
    <div v-if="showItem" class='my_dialog' @click="showDetail(null)">
      <div class='my_dialog_wrap'/>
      <div class='my_dialog_main'>
        <div class='my_dialog_main_header'>
          {{ showItem.packageName }}
          <div>¥{{ showItem.price }}</div>
        </div>
        <div class='my_dialog_main_footer'>
          {{ showItem.dishDetail }}
        </div>
      </div>
    </div>
    <div class="orderFood">
      <div class="orderFood_header">
        <uni-segmented-control :values="segs" activeColor="#b71120" @clickItem="changeTab"
                               :current="current"/>
      </div>

      <div class="orderFood_scroll" v-if="current === 0">
        <div class="time_wrap">
          <div class="time_item">
            <picker mode="date" @change="onDateChange($event,1)" :value="startDate">
              <div class="hxPicker">{{ startDate }}</div>
            </picker>
          </div>
          <div class="time_item">
            <picker mode="date" @change="onDateChange($event,2)" :value="endDate">
              <div class="hxPicker">{{ endDate }}</div>
            </picker>
          </div>
          <div class="time_item">
            <button class="hxButton sm_button" @click="getListInit">确定
            </button>
          </div>
        </div>
        <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" :up="upOption" @up="getList">
          <div class="orderFood_list">
            <div v-for="(item, index) in orderList" :key="index" class="orderFood_list_item">
              <div class="orderFood_list_item_wrap">
                <div class="orderFood_list_item_con">
                  {{ timePipe(item.menuDate, 'MM-DD') }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.mealTimeName }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.packageName }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.takeAddr }}
                </div>
                <div class="orderFood_list_item_con">
                  <button class="hxButton xs_button" @click="toggleDetail(index)">
                    {{ toggleIndex === index ? '收起' : '详情' }}
                  </button>
                </div>
              </div>


              <div class="orderFood_list_detail" v-if="toggleIndex === index">
                <div class="orderFood_list_detail_wrap">
                  <div class="orderFood_list_detail_con">
                    日期：{{ timePipe(item.menuDate) }}
                  </div>
                  <div class="orderFood_list_detail_con">
                    餐次：{{ item.mealTimeName }}
                  </div>
                </div>
                <div class="orderFood_list_detail_con">
                  食堂： {{ item.storeName }}
                </div>
                <div class="orderFood_list_detail_wrap">
                  <div class="orderFood_list_detail_con">
                    套餐名称：{{ item.packageName }}
                  </div>
                  <div class="orderFood_list_detail_con">
                    取餐点：{{ item.takeAddr }}
                  </div>
                </div>
                <div class="orderFood_list_detail_con">
                  菜品明细：{{ item.dishDetail }}
                </div>
                <div class="orderFood_list_detail_footer">
                  <div class="orderFood_list_detail_footer_amount">
                    ¥{{ item.price.toFixed(2) }} x
                    <div class="orderFood_list_detail_footer_amount_wrap">
                      <div class="orderFood_list_detail_footer_amount_wrap_son"/>
                      <uni-number-box v-model="item.quantity"
                                      :disabled="item.isModify=== 'N' || !this.canClick"
                                      @change="modifyQuantity(item)"/>
                    </div>
                  </div>
                  <button v-if="item.isModify === 'Y'" class="orderFood_list_detail_footer_button"
                          @change="cancelOrder(orderList, index)">退订
                  </button>
                  <div v-else>
                    已取餐份数：
                    <div class="orderFood_list_detail_footer_takeCnt">{{ item.takeCnt }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </mescroll-body>
      </div>
      <div class="orderFood_scroll" v-else-if="isCatering">
        <div class="time_wrap">
          <div class="time_item">
            <picker mode="date" @change="onDateChange($event,1)" :value="startDate">
              <div class="hxPicker">{{ startDate }}</div>
            </picker>
          </div>
          <div class="time_item">
            <picker mode="date" @change="onDateChange($event,2)" :value="endDate">
              <div class="hxPicker">{{ endDate }}</div>
            </picker>
          </div>
          <div class="time_item">
            <button class="hxButton sm_button" @click="getListInit">确定
            </button>
          </div>
        </div>
        <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" :up="upOption" @up="getList">
          <div class="orderFood_list">
            <div v-for="(item,index) in orderList" :key="index" class="orderFood_list_item">
              <div class="orderFood_list_item_wrap">
                <div class="orderFood_list_item_con">
                  {{ timePipe(item.menuDate, 'MM-DD') }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.mealTimeName }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.packageName }}
                </div>
                <div class="orderFood_list_item_con">
                  {{ item.takeAddr }}
                </div>
                <div class="orderFood_list_item_con">
                  <button class="hxButton xs_button" @click="toggleDetail(index)">
                    {{ toggleIndex === index ? '收起' : '详情' }}
                  </button>
                </div>
              </div>

              <div class="orderFood_list_detail" v-if="toggleIndex === index">
                <div class="orderFood_list_detail_wrap">
                  <div class="orderFood_list_detail_con">
                    日期：{{ timePipe(item.menuDate) }}
                  </div>
                  <div class="orderFood_list_detail_con">
                    餐次：{{ item.mealTimeName }}
                  </div>
                </div>
                <div class="orderFood_list_detail_con">
                  食堂： {{ item.storeName }}
                </div>
                <div class="orderFood_list_detail_wrap">
                  <div class="orderFood_list_detail_con">
                    套餐名称：{{ item.packageName }}
                  </div>
                  <div class="orderFood_list_detail_con">
                    取餐点：{{ item.takeAddr }}
                  </div>
                </div>
                <div class="orderFood_list_detail_con">
                  菜品明细：{{ item.dishDetail }}
                </div>
                <div class="orderFood_list_detail_footer">
                  <div class="orderFood_list_detail_footer_amount">
                    ¥{{ item.price.toFixed(2) }} x
                    <div class="orderFood_list_detail_footer_amount_wrap">
                      <div class="orderFood_list_detail_footer_amount_wrap_son"/>
                      <uni-number-box type="digit" min="1" max="100" v-model="item.quantity"
                                      :disabled="item.isModify=== 'N' || !this.canClick"
                                      @change="modifyQuantity(item)"/>
                    </div>
                  </div>

                  <button v-if="item.isModify === 'Y'" class="orderFood_list_detail_footer_button"
                          @click="cancelOrder(orderList,index)">退订
                  </button>

                  <div v-else>
                    已取餐份数：
                    <div class="orderFood_list_detail_footer_takeCnt">{{ item.takeCnt }}
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </mescroll-body>
      </div>
      <div class="orderFood_scroll" v-else>
        <div class="orderFood_wrap">
          <div v-for="item in menuHeadList" :key="item.date" class="orderFood_date">
            <div class="orderFood_date_header">{timeWeekPipe(item.menuDate)}
            </div>
            <div v-for="itemSon in item.mealTimeList" class="orderFood_date_item" :key="itemSon.mealTimeId">
              <div class="orderFood_date_item_left">{{ itemSon.mealTimeName }}</div>
              <div class="orderFood_date_item_right">
                <template v-if="itemSon.orderList.length > 0">
                  <div v-for="(itemOrder, index) in itemSon.orderList"
                       class="orderFood_date_item_right_con" :key="itemOrder.packageId">
                    <div class='orderFood_date_item_right_con_left'>
                      <div class='packageName' @click="showDetail(itemOrder)">
                        {{ itemOrder.packageName }}
                      </div>
                      {{ itemOrder.quantity }}份(¥{{ itemOrder.price }})
                      <div class='storeName'>{{ itemOrder.storeName }}
                      </div>
                      {{ itemOrder.takeAddr }}
                    </div>
                    <button class="hxButton xs_button" :disabled="itemSon.isModify=== 'N'"
                            @click="goDetail(item.menuDate, itemSon, index)">更改
                    </button>
                  </div>
                </template>
                <div v-else class="orderFood_date_item_right_con">
                  <div class='orderFood_date_item_right_con_no'>未订餐</div>
                  <button class="hxButton xs_button" :disabled="itemSon.isModify=== 'N'"
                          @click="goDetail(item.menuDate, itemSon, -1)">去订餐
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </hx-page>
</template>

<script>
import {hxParam} from "../../../config/hx-param";
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import {HxPost} from "../../../service/http";
import {getDateAfterDay, getFormatDate, timePipe} from "../../../utils/utils";

export default {
  mixins: [MescrollMixin], // 使用mixin
  data() {
    return {
      canClick: true,
      current: 1,
      cardId: '',
      orderList: [],
      toggleIndex: -1,
      startDate: '',
      endDate: '',
      menuDate: '请选择',
      storeList: [],
      storeListOrigin: [],
      storeSelect: '请选择',
      mealTimeList: [],
      mealTimeListOrigin: [],
      mealSelect: '请选择',
      foodList: [],
      selectFoodNum: -1,
      quantity: 1,
      maxQuantity: 1,
      menuHeadList: [],
      showItem: null,
      isCatering: hxParam.isMealCater,
      segs: ['订餐列表', hxParam.isMealCater ? '退餐记录' : '预订餐']
    };
  },
  onShow() {
    this.cardId = hxParam.cardId;
    if (this.cardId) {
      this.current = 1;
      this.changeTab();
    } else {
      uni.switchTab({url: '/pages/personCenter/index'})
          .then(() => {
            uni.showToast({
              title: '请先绑定卡片',
              icon: 'none',
              duration: 3 * 1000
            });
          }).catch();
    }
  },
  methods: {
    timePipe,
    onDateChange(e, index) {
      let nowDate = e.detail.value;
      if (index === 1) {
        if (nowDate !== this.startDate) {
          this.startDate = nowDate
        }
      } else {
        if (nowDate !== this.endDate) {
          this.endDate = nowDate
        }
      }
    },

    changeTab() {
      this.pageNo = 1;
      if (this.current === 0) {
        this.startDate = getFormatDate();
        this.endDate = getDateAfterDay(30);
        this.getListInit();
      } else if (hxParam.isMealCater) {
        this.startDate = getFormatDate();
        this.endDate = getDateAfterDay(30);
        this.getListInit();
      } else {
        this.getOrderList();
      }
    },

    getOrderList() {
      this.menuDate = '请选择';
      this.storeList = [];
      this.storeListOrigin = [];
      this.storeSelect = '请选择';
      this.mealTimeList = [];
      this.mealTimeListOrigin = [];
      this.mealSelect = '请选择';
      this.foodList = [];
      this.selectFoodNum = -1;
      this.quantity = 1;
      this.menuHeadList = [];
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
          .then(() => {
            return HxPost('orderFoodListAll', {
              cardId: this.cardId
            });
          })
          .then((res) => {
            uni.hideLoading();
            this.menuHeadList = res.menuHeadList
          })
          .catch((err) => {
            console.log('err', err)
            uni.hideLoading();
            uni.showToast({
              title: err.retMsg || '未知错误',
              icon: 'none',
              duration: 3 * 1000
            }).catch();
          });
    },

    getListInit() {
      this.orderList = [];
      this.toggleIndex = -1;
      this.mescroll.scrollTo(0, 0);
      this.mescroll.triggerDownScroll();
    },

    getList(page) {
      /*  if (!this.isFirst) {
          this.mescroll.scrollTo(0, 0)
          this.mescroll.triggerDownScroll()
        }*/
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
          .then(() => {
            let param = {
              cardId: this.cardId,
              pageNo: page.num,
              pageSize: page.size,
              startDate: this.startDate.split('-').join(''),
              endDate: this.endDate.split('-').join(''),
            };
            return HxPost('orderFoodList', param);
          })
          .then((res) => {
            uni.hideLoading();
            if (res['orderList'] && res['orderList'].length > 0) {
              this.mescroll.endSuccess(res['orderList'].length);
              this.orderList = this.orderList.concat(res['orderList'])
            } else {
              this.mescroll.endSuccess(0);
              uni.showToast({
                title: '未查询到更多订餐记录',
                icon: 'none',
                duration: 3 * 1000
              }).catch();
            }
          })
          .catch((err) => {
            console.log('err1', err)
            this.mescroll.endErr();
            uni.hideLoading();
            uni.showToast({
              title: err.retMsg || '未知错误',
              icon: 'none',
              duration: 3 * 1000
            }).catch();
          });
    },

    cancelOrder(orderList, index) {
      this.orderFood(orderList[index], 'D')
          .then(() => {
            orderList.splice(index, 1);
            this.orderList = orderList
          })
          .catch(() => {
          });
    },

    toggleDetail(index) {
      this.toggleIndex = this.toggleIndex === index ? -1 : index
    },

    orderFood(item, action) {
      let msg = '确定预订餐吗？';
      if (action === 'M') {
        msg = '确定修改订餐吗？';
      }
      if (action === 'D') {
        msg = '确定退订该笔订餐吗？';
      }
      return uni.showModal({
        title: '',
        content: msg,
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定'
      })
          .then((res) => {
            if (res.confirm) {
              return uni.showLoading({
                title: '加载中...',
                mask: true
              });
            } else {
              return Promise.reject('cancel');
            }
          })
          .then(() => {
            return HxPost('orderFood', {
              menuDate: action === 'A' ? this.menuDate.split('-').join('') : item['menuDate'],
              cardId: this.cardId,
              storeId: action === 'A' ? getJsonKeyByKey(this.storeListOrigin, 'storeId', 'storeName', this.storeSelect) : item['storeId'],
              mealTimeId: action === 'A' ? getJsonKeyByKey(this.mealTimeListOrigin, 'mealTimeId', 'mealTimeName', this.mealSelect) : item['mealTimeId'],
              packageId: item['packageId'],
              quantity: item['quantity'],
              mealOrderId: action === 'A' ? '' : item['mealOrderId'],
              opFlag: action
            });
          })
          .then((res) => {
            uni.hideLoading();
            if (action === 'A') {
              item.amountQuantity = Number(item.amountQuantity) + Number(item.quantity);
              let newFoodList = this.foodList;
              let selectNum = this.selectFoodNum;
              newFoodList[selectNum].amountQuantity = item.amountQuantity;

              this.foodList = newFoodList
              this.selectFoodNum = -1
              this.maxQuantity = Number(item.tatolQuantity) - Number(item.amountQuantity)
            }
            uni.showToast({
              title: res.retMsg,
              icon: 'none',
              duration: 3 * 1000
            }).catch();
            return Promise.resolve();
          })
          .catch((err) => {
            console.log('err3', err)
            if (err !== 'cancel') {
              uni.hideLoading();
              uni.showToast({
                title: err.retMsg || '未知错误',
                icon: 'none',
                duration: 3 * 1000
              }).catch();
            }
            return Promise.reject(err);
          });
    },


    modifyQuantity(item, e) {
      if (this.canClick) {
        this.canClick = false;
        let param = Object.assign({}, item);
        item.quantity = e;
        this.orderFood(item, 'M')
            .then(() => {
              this.canClick = true;
            })
            .catch(() => {
              item.quantity = param.quantity;
              this.canClick = true;
            });
      }
    },

    goDetail(date, param, index) {
      let url =
          `/pages/orderFoodDetail/index?cardId=${this.cardId}&date=${date}&index=${index}&param=${JSON.stringify(param)}`
      uni.navigateTo({
        url: url
      }).catch();
    },

    showDetail(itemOrder) {
      this.showItem = itemOrder
    },
  }
};
</script>

<style lang="scss" scoped>
$color-border: #e1e1e1;
$color0: #000;
$color1: #b71120;
$color2: #FFF;
$color3: #6a6a77;
$color4: #333;
$color5: #999;

.orderFood {
  &_header {
    margin: 0 20PX;
  }

  &_scroll {
    display: flex;
    flex: 1;
    width: 100%;
    flex-direction: column;
    //overflow: hidden;

    .time_wrap {
      display: flex;
      flex-direction: row;
      margin-top: 5PX;
      margin-bottom: 5PX;
      border-top: 1PX solid #e1e1e1;
      border-bottom: 1PX solid #e1e1e1;

      .time_item {
        display: flex;
        flex: 1;
        border-left: 1PX solid #e1e1e1;
        justify-content: center;
        line-height: 1.5;
        font-size: 15PX;
        padding: 3PX 0;
      }

      .time_item:nth-child(1) {
        border-left: none;
      }
    }

    &_select {
      height: 100%;
      overflow: auto;
    }

    &_bottom {
      display: flex;
      //justify-content: space-between;
      background: $color2;

      &_left {
        display: flex;
        flex: 1;
        border-top: 1PX solid $color-border;
        align-items: center;
        padding-left: 20PX;
        color: $color1;
      }

      &_button {
        color: white;
        border: none;
        background: $color1;
        width: 80PX;
        height: 100%;
        border-radius: 0;
      }
    }
  }

  &_list {
    background: $color2;
    border-bottom: 1PX solid $color-border;

    &_item {
      display: flex;
      flex-direction: column;
      border-bottom: 1PX solid $color-border;
      padding: 10PX 15PX;
      font-size: 14PX;

      &_wrap {
        display: flex;
        flex-direction: row;
        font-weight: 700;
        color: $color0;
        align-items: center;
      }

      &_con {
        display: flex;
        justify-content: center;
      }

      &_con:nth-child(1) {
        width: 45PX;
      }

      &_con:nth-child(2) {
        width: 35PX;
      }

      &_con:nth-child(3) {
        //flex: 1;
        padding: 0 2PX;
      }

      &_con:nth-child(4) {
        flex: 1;
      }

      &_con:nth-child(5) {
        width: 50PX;
      }
    }

    &_detail {
      display: flex;
      flex-direction: column;
      margin-top: 10PX;
      padding: 10PX 5PX;
      border-top: 1PX solid $color-border;
      font-size: 14PX;

      &_wrap {
        display: flex;
        justify-content: space-between;
      }

      &_con {
        padding-bottom: 5PX;
      }

      &_footer {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        &_amount {
          display: flex;
          align-items: center;
          color: $color1;

          &_wrap {
            margin-left: 10PX;
            position: relative;
            overflow: hidden;

            &_son {
              position: absolute;
              left: 50%;
              top: 0;
              width: 36PX;
              height: 25PX;
              margin-left: -18PX;
              z-index: 100;
            }
          }
        }

        &_takeCnt {
          display: inline-block;
          color: $color1;
        }

        &_button {
          color: white;
          border-color: $color-border;
          background: $color1;
          width: 100%;
          height: 26PX;
          line-height: 26PX;
        }
      }
    }
  }

  &_order {
    background: $color2;
    margin-top: 20PX;

    &_select {
      font-size: 14PX;
      background: $color2;

      &_title {
        position: relative;
        padding: 6PX 15PX;
        color: $color3;
      }

      &_title::before {
        content: "";
        display: inline-block;
        position: absolute;
        left: 8PX;
        top: 50%;
        margin-top: -8PX;
        width: 2PX;
        height: 16PX;
        background-color: $color1;
      }

      &_con {
        padding: 6PX 15PX;
        border-top: 1PX solid $color-border;
        border-bottom: 1PX solid $color-border;
      }


      &_list {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        border-bottom: none;

        &_tips {
          color: $color1;
        }

        &_item {
          display: flex;
          width: 31%;
          margin-right: 2.3%;
          color: $color1;
          border: 1PX solid $color1;
          border-radius: 5PX;
          margin-bottom: 5PX;
          flex-direction: column;

          &_header {
            font-weight: 700;
            border-bottom: 1PX solid $color1;
            justify-content: center;
            text-align: center;
            padding: 2PX 0;
          }

          &_con {
            padding: 2PX;
          }
        }

        &_item_active {
          background: $color1;
          color: $color2;

          .orderFood_order_select_list_item_header {
            border-bottom: 1PX solid $color2;
          }
        }

        &_item_disable {
          background: $color5;
          color: $color3;
        }
      }

    }

    &_picker {
      display: flex;
      justify-content: space-between;

      &_left {
        color: $color4;
      }

      &_right {
        color: $color5;
      }
    }
  }

  &_wrap {
    width: 100%;
    flex-grow: 0;
    overflow-y: auto;
  }

  &_date {
    margin-top: 4PX;
    background-color: #FFFFFF;
    border-top: 1PX solid #e8e8e8;
    font-size: 14PX;

    &_header {
      border-bottom: 1PX solid #e8e8e8;
      padding: 5PX 15PX;
      background-color: aliceblue;
      font-weight: 700;
      color: $color0;
    }

    &_item {
      border-bottom: 1PX solid #e8e8e8;
      padding: 5PX 15PX;
      display: flex;

      &_left {
        margin-right: 10PX;
      }

      &_right {
        flex: 1;
        display: flex;
        flex-direction: column;

        &_con {
          display: flex;

          &_no {
            flex: 1;
            color: $color1;
          }

          &_left {
            flex: 1;

            .packageName {
              color: #22b13f;
              display: inline-block;
              margin-right: 10PX;
            }

            .storeName {
              display: inline-block;
              margin: 0 10PX;
            }
          }
        }
      }
    }
  }
}
</style>
